function escapefields(str) {
	out = str.replace(/&/gi, '<@#>');
	//out = out.replace(/<p>/gi, '');
	//out = out.replace(/<\/p>/gi, '<br />');
	return out;
}

function editarea(id, page) {
	//var button = Ext.get('edit-button-'+id);
	dlgwidth = 500;
	dlgheight = 300;
	if (id == 0) 
		dlgcontent = 'Страница находится в разработке..';
	else 
		dlgcontent = $('#editable-content-' + id).html();
	
	var dlgitems = [{
		xtype: "tinymce",
		tinymceSettings: {
			convert_newlines_to_brs: true,
			force_br_newlines: true,
			force_p_newlines: false,
			forced_root_block: '',
			theme: "advanced",
			skin: "o2k7",
			width: "100%",
			height: "454",
			content_css: templatefolder + "styles.css",
			plugins: "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,template,images",
			theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,outdent,indent,blockquote,undo,redo,|,link,unlink,anchor,images,cleanup,help,code",
			theme_advanced_buttons2: "styleselect,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor",
			theme_advanced_buttons3: "",
			theme_advanced_buttons4: "",
			theme_advanced_toolbar_location: "top",
			theme_advanced_toolbar_align: "left",
			theme_advanced_statusbar_location: "",
			theme_advanced_resizing: false,
			extended_valid_elements: "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|style],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
			template_external_list_url: "example_template_list.js"
		},
		value: dlgcontent
	}];
	
	
	if (page != '') {
		dlgwidth = 800;
		dlgheight = 550;
	}
	
	var dlg = new Ext.Window({
		title: 'Редактировать страницу',
		width: dlgwidth,
		height: dlgheight,
		minWidth: 300,
		minHeight: 300,
		constrain: true,
		y: (navigator.userAgent.indexOf('Firefox') != -1 ? (scrollY + 60) : (document.body.scrollTop + 60)),
		layout: "fit",
		modal: false,
		resizable: true,
		maximizable: true,
		closeAction: "hide",
		hideMode: "offsets",
		constrainHeader: true,
		items: dlgitems,
		buttons: [{
			text: 'Сохранить',
			disabled: false,
			handler: function() {
				var content = tinyMCE.activeEditor.getContent();
				var areacontent = escapefields(content);
				editscript = 'editarea.php';
				if (page != '') {
					editscript = 'editpage.php';
					page = '/' + page;
				}
				else {
					page = templatepath;
				}
				$.post(panelpath + editscript, 'text=' + areacontent + '&path=' + page + '&editarea-id=' + id, function(data) {
					if (data == 'yes') {
						$('#editable-content-' + id).html(content);
						dlg.hide();
						if (editscript == 'editpage.php') 
							location.href = page;
					}
					else {
						alert(data);
					}
				}, "text");
				
			}
		}, {
			text: 'Отчистить',
			handler: function() {
				tinyMCE.activeEditor.setContent('');
			}
		}, {
			text: 'Закрыть',
			handler: function() {
			
				dlg.hide();
			}
		}]
	});
	dlg.show();
}


function editcontent(page) {
	frompage = arguments[1];
	var myMask = new Ext.LoadMask(Ext.getBody(), {
		msg: "Пожалуйста подождите."
	});
	myMask.show();
	if (!frompage) 
		frompage = page;
	$.post(panelpath + 'getpage.php', 'path=' + frompage, function(data) {
		var dlgitems = [{
			xtype: "tinymce",
			tinymceSettings: {
				convert_newlines_to_brs: true,
				force_br_newlines: true,
				force_p_newlines: false,
				forced_root_block: '',
				theme: "advanced",
				skin: "o2k7",
				width: "100%",
				height: "454",
				content_css: templatefolder + "styles.css",
				plugins: "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,template,images",
				theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,outdent,indent,blockquote,undo,redo,|,link,unlink,anchor,images,cleanup,help,code",
				theme_advanced_buttons2: "styleselect,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor",
				theme_advanced_buttons3: "",
				theme_advanced_buttons4: "",
				theme_advanced_toolbar_location: "top",
				theme_advanced_toolbar_align: "left",
				theme_advanced_statusbar_location: "",
				theme_advanced_resizing: false,
				extended_valid_elements: "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|style],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
				template_external_list_url: "example_template_list.js",
				relative_urls : false,
				remove_script_host : true,
				language : "ru"

			},
			value: data
		}];
		
		if (page != '') {
			dlgwidth = 800;
			dlgheight = 550;
		}
		
		var dlg = new Ext.Window({
			title: 'Редактировать страницу',
			width: dlgwidth,
			height: dlgheight,
			minWidth: 300,
			minHeight: 300,
			constrain: true,
			y: (navigator.userAgent.indexOf('Firefox') != -1 ? (scrollY + 60) : (document.body.scrollTop + 60)),
			layout: "fit",
			modal: false,
			resizable: true,
			maximizable: true,
			closeAction: "hide",
			hideMode: "offsets",
			constrainHeader: true,
			items: dlgitems,
			buttons: [{
				text: 'Сохранить',
				disabled: false,
				handler: function() {
					$.post(panelpath + 'editpage.php', 'path=' + page + '&frompath=' + frompage + '&text=' + escapefields(tinyMCE.activeEditor.getContent()), function(data) {
						if (data == 'yes') {
							dlg.hide();
							location.reload();
						}
						else {
							alert(data);
						}
					}, "text");
					
				}
			}, {
				text: 'Восстановить',
				handler: function() {
					//tinyMCE.activeEditor.setContent('');
					
					//backups=[[1,'17.02.2009 11:30'],[2,'17.02.2009 11:30']];
					var store = new Ext.data.SimpleStore({
						fields: [{
							name: 'check'
						}, {
							name: 'date',
							type: 'date',
							dateFormat: 'timestamp'
						}, ]
					});
					
					var grid = new Ext.grid.GridPanel({
						store: store,
						disableSelection: true,
						sm: new Ext.grid.RowSelectionModel({
							singleSelect: true
						}),
						
						//onrowclick : function (grid2, rowIndex, e) {alert('wow');},
						columns: [{
							header: "#",
							width: 40,
							dataIndex: 'check',
							renderer: function(value, p, r) {
								return value;
							},
							sortable: false
						}, {
							header: "Дата",
							width: 120,
							dataIndex: 'date',
							renderer: function(value, p, r) {
								return value.dateFormat('d.m.Y h:i');
							},
							sortable: true
						}],
						width: '100%',
						height: 230
					});
					
					var restore = new Ext.Window({
						title: 'Восстановить бекап',
						width: 200,
						height: 300,
						resizable: false,
						maximizable: false,
						items: grid,
						buttons: [{
							text: 'Восстановить',
							handler: function() {
								var selectionModel = grid.getSelectionModel();
								var record = selectionModel.getSelected();
								if (record) 
									Ext.MessageBox.confirm('Восстановить бекап?', 'Вы уверены, что хотите восстановить бекап сделанный <span style="color:#FF0000;">' + record.get('date').dateFormat('d.m.Y') + '</span> в <span style="color:#FF0000;">' + record.get('date').dateFormat('H:i:s') + '</span>?', function(btnpressed) {
										if (btnpressed == 'yes') {
											myMask.show();
											$.post(panelpath + 'restorebackups.php', 'restore=' + record.get('check') + '&path=' + page, function(data) {
												if (data == 'no') {
													myMask.hide();
													Ext.MessageBox.alert('Восстановление', 'Бекап не найден!', function() {
													});
												}
												else {
													restore.close();
													dlg.close();
													editcontent(page, data);
													myMask.hide();
												}
											//store.loadData(backups);
											//myMask.hide();
											}, "text");
										}
									});
								else 
									Ext.MessageBox.alert('Восстановление', 'Вы не выбрали бекап для восстановления!', function() {
									});
								//alert(record.get('check'));
							},
							//iconCls: 'new-tab',
							style: 'margin:3px auto;'
						}, {
							text: 'Отменить',
							handler: function() {
								restore.close()
							},
							//iconCls: 'new-tab',
							style: 'margin:3px auto;'
						}]
					});
					restore.show();
					myMask.show();
					$.post(panelpath + 'restorebackups.php', 'path=' + page, function(data) {
						eval(data);
						store.loadData(backups);
						myMask.hide();
					}, "text");
					
				}
			}, {
				text: 'Закрыть',
				handler: function() {
				
					dlg.hide();
				}
			}]
		});
		
		dlg.show();
		
		myMask.hide();
	});
	
}


function addpage() {
	var form = new Ext.form.FormPanel({
		baseCls: 'x-plain',
		labelWidth: 155,
		url: 'save-form.php',
		defaultType: 'textfield',
		
		items: [{
			fieldLabel: 'Название страницы',
			name: 'title',
			anchor: '100%' // anchor width by percentage
		}, {
			fieldLabel: 'Заголовок страницы',
			name: 'h1',
			anchor: '100%' // anchor width by percentage
		}, {
			fieldLabel: 'Адрес страницы',
			name: 'path',
			value: 'pagename.php',
			anchor: '100%' // anchor width by percentage
		}, {
			fieldLabel: 'Ключевые слова',
			name: 'keywords',
			anchor: '100%' // anchor width by percentage
		}, {
			fieldLabel: 'Описание',
			xtype: 'textarea',
			name: 'description',
			anchor: '100%' // anchor width by percentage
		}]
	});
	
	var window = new Ext.Window({
		title: 'Создание новой страницы',
		width: 500,
		height: 245,
		minWidth: 300,
		minHeight: 200,
		y: (navigator.userAgent.indexOf('Firefox') != -1 ? (scrollY + 110) : (document.body.scrollTop + 110)),
		layout: 'fit',
		plain: true,
		bodyStyle: 'padding:5px;',
		buttonAlign: 'center',
		items: form,
		
		buttons: [{
			text: 'Создать',
			handler: function() {
				values = form.getForm().getValues();
				$.post(panelpath + 'addpage.php', 'title=' + escapefields(values['title']) + '&h1=' + escapefields(values['h1']) + '&path=' + values['path'] + '&keywords=' + escapefields(values['keywords']) + '&description=' + escapefields(values['description']), function(data) {
					if (data == 'yes') {
						window.hide();
						editarea(0, values['path']);
					}
					else {
						alert(data);
					}
				}, "text");
				
			}
		}, {
			text: 'Отмена',
			handler: function() {
				window.hide();
			}
		}]
	});
	window.show();
}


function editpage() {
	$.post(panelpath + 'editproperties.php', 'path=' + pagepath, function(data) {
		eval(data);
		var form = new Ext.form.FormPanel({
			baseCls: 'x-plain',
			labelWidth: 155,
			url: 'save-form.php',
			defaultType: 'textfield',
			
			items: [{
				fieldLabel: 'Название страницы',
				name: 'title',
				anchor: '100%',
				value: out['title']
			}, {
				fieldLabel: 'Заголовок страницы',
				name: 'h1',
				anchor: '100%',
				value: out['h1']
			}, {
				fieldLabel: 'Ключевые слова',
				name: 'keywords',
				anchor: '100%',
				value: out['keywords']
			}, {
				fieldLabel: 'Описание',
				xtype: 'textarea',
				name: 'description',
				anchor: '100%',
				value: out['description']
			}]
		});
		
		var window = new Ext.Window({
			title: 'Редактирование свойств страницы ' + pagepath,
			width: 500,
			height: 218,
			minWidth: 300,
			minHeight: 200,
			y: (navigator.userAgent.indexOf('Firefox') != -1 ? (scrollY + 110) : (document.body.scrollTop + 110)),
			layout: 'fit',
			plain: true,
			bodyStyle: 'padding:5px;',
			buttonAlign: 'center',
			items: form,
			
			buttons: [{
				text: 'Сохранить',
				handler: function() {
					values = form.getForm().getValues();
					window.hide();
					$.post(panelpath + 'editproperties.php', 'title=' + escapefields(values['title']) + '&h1=' + escapefields(values['h1']) + '&path=' + pagepath + '&keywords=' + escapefields(values['keywords']) + '&description=' + escapefields(values['description']), function(data) {
						if (data == 'yes') {
							location.reload();
						}
						else {
							alert(data);
						}
					}, "text");
					
				}
			}, {
				text: 'Отмена',
				handler: function() {
					window.hide();
				}
			}]
		});
		window.show();
	}, "text");
	
}
